const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
var jwt = require('jsonwebtoken');


/* GET users listing. */
const User = require('../models/User');
const Book = require("../models/Book");
const Content = require("../models/booksContent");
const Ping = require("../models/PingLun");
const History = require("../models/History")
const Ju = require("../models/Jubao")
// const passport = require('passport');
//举报功能
router.post('/jubao/:id', (req, res) => {
  let newJu = new Ju({
    bookid: req.body.bookid,
    userid: req.params.id,
    reason: req.body.reason
  })
  newJu.save()
  .then(res.sendStatus(200))
})
//用户注册
router.post('/zhuce', (req, res) => {
  User.findOne({ zhanghao: req.body.zhanghao })
    .then((user) => {
      if (user) {
        return res.status(400).json({ msg: '该账号已被注册' })
      } else {
        let newUser = new User({
          zhanghao: req.body.zhanghao,
          username: req.body.username,
          password: req.body.password,
          email: req.body.email
        })
        bcrypt.genSalt(10, function (err, salt) {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser.save()
              .then(user => res.json({ status: 200 }))
              .catch(err => res.json(err));
          });
        });
      }
    });
});

//添加用户浏览记录
router.post("/newHistory/:id", (req, res) => {
  History.find({ userid: req.params.id, bookid: req.body.bookid })
    .then(T => {
      if (T[0] != null) {
        History.updateOne({ userid: req.params.id, bookid: req.body.bookid }, { $set: { date: new Date() } })
          .then(res.sendStatus(200))
          .catch(err => console.log(err))
        return
      } else {
        History.find({ userid: req.params.id }).countDocuments(true)
          .then(num => {
            let newHistory = new History({
              date:new Date(),
              userid: req.params.id,
              bookid: req.body.bookid,
            })
            newHistory.save()
              .then(() => {
                if (num < 10) {
                  //console.log(2);
                  res.sendStatus(200);
                  return
                } else {
                  //console.log(3);
                  History.deleteOne({ userid: req.params.id }).sort({ date: -1 })
                    .then(res.sendStatus(200))
                    .catch(err => console.log(err))
                  return
                }
              })
              .catch(err => console.log(err))
          })
          .catch(err => console.log(err))
        return
      }
    })
  //console.log(new Date());
  // res.sendStatus(200)
  // let newHistory = new History({
  //   userid: req.params.id,
  //   bookid: req.body.bookid,
  // })
  // newHistory.save()
  //   .then((result) => {
  //     History.find({ userid:req.params.id }).countDocuments(true)
  //       .then(num => {
  //         if (num < 101) {
  //           res.sendStatus(200);
  //           return
  //         } else {
  //           History.deleteOne({ userid: req.params.id }).sort({ date: 1 })
  //             .then(res.sendStatus(200))
  //         }
  //       })
  //   }).catch((err) => {
  //     console.log(err);
  //   });
})
//获取用户历史记录
router.get("/thisUserHistory/:id", (req, res) => {
  History.find({ userid: req.params.id }).sort({date:-1})
    .then(h => {
      let bid = [];
      let bti = [];
      let p = new Promise(() => {
        h.forEach((item,i) => {
          bid[i] = item.bookid
          bti[i] = item.date
        });
      })
      p.then(
        //console.log(bid),
        Book.find({ _id:bid}, { bookname: 1, avatar: 1, date: 1 })
          .then(book => {
            //console.log(book);
            let p1 = new Promise(() => {
              bti.forEach((item, i) => {
              book[i].date = item
            });
            })
            p1.then(res.send({data:book,status:200}))
          })
  
      )
    })
})

//删除用户
router.delete('/thisUser/:id', (req, res) => {
  User.findByIdAndDelete(req.params.id)
    .then(res.sendStatus(200))
})

//用户登录
router.post('/login', (req, res) => {
  const zhanghao = req.body.zhanghao;
  const password = req.body.password;
  User.findOne({ zhanghao })
    .then(user => {
      if (!user) {
        return res.json({ msg: '账号不存在' })
      }
      //return username;
      bcrypt.compare(password, user.password)
        .then(isMatch => {
          if (isMatch) {
            // jwt.sign("规则"，加密名字，过期时间(s)，箭头函数)
            const rule = {
              id: user.id,
              zhanghao: user.zhanghao,
            }
            jwt.sign(rule, "thek", { expiresIn: 72000 }, (err, token) => {
              if (err) throw err;
              res.json({
                data: {
                  id: user.id,
                  avatar: user.avatar,
                  username: user.username,
                  state: user.state
                },
                status: 200,
                token: 'Bearer ' + token
              })
            })
          } else {
            res.json({
              status: 400,
              msg: '用户信息错误'
            })
          }
        })
    })
})
//用户获取自己的信息
router.get("/userGetUserData/:id", (req, res) => {
  User.findById(req.params.id, { avatar: 1, username: 1, email: 1, state: 1 })
    .then(user => res.send({ data: user, status: 200 }))
    .catch(err => console.log(err))
})

//管理员获取全部用户信息
router.post("/showUsers", (req, res) => {
  //console.log(req.body);
  let a = req.body.pageSize;
  let b = req.body.currentPage
  let c = (b - 1) * a;
  User.find({}, { username: 1, date: 1, state: 1, email: 1 }).skip(c).limit(a)
    .then(user => {
      User.find().countDocuments(true)
        .then(num => res.send({ data: user, num: num, status: 200 }))
    })
})

//更换头像
router.post("/changeUserAvatar/:id", (req, res) => {
  //url = `http://127.0.0.1:3000/uploads/users/${req.body.avatar}`
  User.findByIdAndUpdate(req.params.id, { $set: { avatar: req.body.avatar } })
    .then(user => res.send({ data: user.avatar, status: 200 }))
})

router.post("/updateState/:id", (req, res) => {
  //console.log(req.body);
  let state = req.body.state;
  //console.log(state);
  User.findByIdAndUpdate({ _id: req.params.id }, { $set: { state } }, { new: true })
    .then(user => res.json({ status: 200 }))
})

//读者获取书架的相关信息和最新章节
//先用读者id查询书架，再用书架中书籍id查询具体书籍的部分信息，然后继续用书籍id查询全部章节，再根据书籍id分组
//获取到最后一条信息，及最后更新的章节，然后创建一个异步方法，遍历出章节名并且添加到书籍相关信息提前准备好的空白字段中
//返回客户端
router.get("/shoucang/:id", (req, res) => {
  User.findById({ _id: req.params.id }, { shujia: 1 })
    .then(shu => {
      Book.find({ _id: shu.shujia }, { bookname: 1, avatar: 1, isend: 1, state: 1, thelast: 1 })
        .then(b => {
          Content.aggregate([{ $match: { bookid: { $in: shu.shujia } } }, { $group: { _id: "$bookid", last: { $last: "$title" } } }])
            .then(c => {
              //for (let i = 0; i < b.length; i++){
              let p = new Promise((res, rej) => {
                for (let j = 0; j < c.length; j++) {
                  b[j].thelast = c[j].last
                }
              })
              p.then(res.send({ data: b, status: 200 }))
            }
            )
        })
    })
})
//Content.find({ bookid: shu.shujia }, { title: 1 }).sort({date:-1}).limit(1)

//是否搜藏本书
router.post("/isInShuJia/:id", (req, res) => {
  User.findById({ _id: req.params.id }, { shujia: 1 })
    .then(shu => {
      //console.log(shu);
      if (shu.shujia.includes(req.body.bookid)) {
        res.sendStatus(200)
        return
      } else {
        res.json('NO')
        return
      }
    })
})

//添加收藏
router.post("/addSoucang/:id", (req, res) => {
  User.findByIdAndUpdate({ _id: req.params.id }, { $addToSet: { shujia: req.body.bookid } })
    .then(
      Book.updateOne({ _id: req.body.bookid }, { $inc: { thiscollection: 1 } })
        .then(res.sendStatus(200))
        .catch(err => console.log(err))
    )
})
//取消收藏
router.post("/removeShoucang/:id", (req, res) => {
  //console.log(req.params.id);
  User.findByIdAndUpdate({ _id: req.params.id },
    { $pull: { shujia: req.body.bookid } })
    .then(Book.updateOne({ _id: req.body.bookid }, { $inc: { thiscollection: -1 } })
      .then(res.sendStatus(200))
      .catch(err => console.log(err)))
})

//更改用户信息
router.post("/updata/:id", (req, res) => {
  const userdata = {};
  if (req.body.username) { userdata.username = req.body.username };
  if (req.body.password) { userdata.password = req.body.password };
  if (req.body.email) { userdata.email = req.body.email };
  if (userdata.password != null) {
    bcrypt.genSalt(10, function (err, salt) {
      bcrypt.hash(userdata.password, salt, (err, hash) => {
        if (err) throw err;
        userdata.password = hash;
        User.findOneAndUpdate(
          { _id: req.params.id },
          { $set: userdata },
          { new: true }
        ).then(res.sendStatus(200))
      });
    })
  }
  if (userdata.password == null) {
    User.findOneAndUpdate(
      { _id: req.params.id },
      { $set: userdata },
      { new: true }).then(res.sendStatus(200))
  }
})

//用户展示主页
router.get("/touser/:id", (req, res) => {
  User.findById(req.params.id, {
    avatar: 1, state: 1, username: 1, date: 1
  })
    .then(user =>
      Ping.find({ userid: req.params.id, state: 1 }, { bookid: 1, date: 1, text: 1 })
        .then(ping => res.send({ data: { user, ping }, status: 200 }))
    )
})

// 根据书籍id查询黑名单 并且获得部分信息
router.get('/thisBookHei/:id', (req, res) => {
  Book.findById(req.params.id, { hei: 1 })
    .then(book => {
      User.find({ _id: book.hei }, { username: 1 })
        .then(user => res.send({ data: user, status: 200 }))
    })
})
module.exports = router;
